from django.http import HttpResponse
# from django.utils.deprecation import MiddlewareMixin
from django_redis import get_redis_connection

from common.utils import get_ip_address


# class TestMiddleware(MiddlewareMixin):
#
#     @staticmethod
#     def process_request(request):
#         print('请求来了')
#
#     @staticmethod
#     def process_view(request, view_func, view_args, view_kwargs):
#         print(f'准备执行{view_func.__name__}')
#
#     @staticmethod
#     def process_template_response(request, response):
#         print('准备渲染模板')
#         return response
#
#     @staticmethod
#     def process_response(request, response):
#         print('返回响应')
#         return response
#
#     @staticmethod
#     def process_exception(request, exception):
#         print('出现异常')


# class BlackListMiddleware:
#
#     def __init__(self, view_func):
#         self.view_func = view_func
#
#     def __call__(self, request, *args, **kwargs):
#         ip = get_ip_address(request)
#         redis_cli = get_redis_connection()
#         if redis_cli.sismember('zhipin:common:middlewares:black_list', ip):
#             resp = HttpResponse(status=403)
#         else:
#             resp = self.view_func(request, *args, **kwargs)
#         return resp


def black_list_middleware(get_resp):

    def middleware(request, *args, **kwargs):
        ip = get_ip_address(request)
        redis_cli = get_redis_connection()
        if redis_cli.sismember('zhipin:common:middlewares:black_list', ip):
            resp = HttpResponse(status=403)
        else:
            resp = get_resp(request, *args, **kwargs)
        return resp

    return middleware
